/* 
 * lotura - GWT databinding
 * Copyright (C) 2008  Juanjo García Latre
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package net.inttes.lotura.binding.convert.support;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.inttes.lotura.binding.convert.ConversionService;
import net.inttes.lotura.binding.convert.Converter;
import net.inttes.lotura.core.closure.Closure;


public class DefaultConversionService implements ConversionService {

	private List converters = new ArrayList();
	
	
	public DefaultConversionService() {
		addDefaultConverters();
	}
	
	
	protected void addDefaultConverters() {
		addConverter( new NumberToString() );
		addConverter( new StringToDouble() );
		addConverter( new StringToInteger() );
	}
	
	
	public void addConverter(Converter converter) {
		converters.add(converter);
	}
	
	
	public Closure getConversionClosure(String sourceClass, String targetClass) {
		for (Iterator ite = converters.iterator(); ite.hasNext();) {
			Converter converter = (Converter) ite.next();
			if (contains(converter.getSourceClasses(), sourceClass) &&
					contains(converter.getTargetClasses(), targetClass)) {
				return new ConverterClosure(converter, targetClass);
			}
		}
		return null;
	}

	
	private static class ConverterClosure implements Closure {
		private Converter converter;
		private String targetClass;
		
		public ConverterClosure(Converter converter, String targetClass) {
			this.converter = converter;
			this.targetClass = targetClass;
		}
		
		public Object call(Object source) {
			return converter.convert(source, targetClass, null);
		}		
	}

	
	private static boolean contains(String[] classes, String claz) {
		for (int i = 0; i < classes.length; i++) {
			if (classes[i].equals(claz)) {
				return true;
			}
		}
		return false;
	}
	
}
